package com.jianganming.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class HttpServer {
    public static void main(String[] args) {
        EventLoopGroup group1 = new NioEventLoopGroup(1);
        EventLoopGroup group2 = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group1,group2)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new MyChannelInitializer());
            ChannelFuture future = bootstrap.bind(8484).sync();
            future.channel().closeFuture().sync();
        }catch (Exception e){

        }
    }
}

class MyChannelInitializer extends ChannelInitializer<SocketChannel>{

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //处理http请求的解码器
        pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
        pipeline.addLast("MyHttpServerHandler",new HttpServerHandler());
    }
}

/**
 * HttpObject 是客户端和服务端通信的数据
 */
class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject>{

    @Override
    protected void channelRead0(ChannelHandlerContext cx, HttpObject httpObject) throws Exception {
        if(httpObject instanceof HttpRequest) {
            System.out.println(cx.channel().remoteAddress());
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello,我是服务端", CharsetUtil.UTF_8);
            FullHttpResponse httpResponse =
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK, byteBuf);
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
            cx.writeAndFlush(httpResponse);
        }
    }
}